package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.MyUserLoginResponse;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dto.UserLoginResponseGet;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.IKaptchaService;
import com.cskaoyan.user.service.ILoginService;
import com.cskaoyan.user.utils.AesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author Aaliyah
 * @date 2022/9/21 17:57
 * @description: TODO
 */
@Service
public class LoginServiceImpl implements ILoginService {

    // token过期时间和相关的路径
    private static final Long MAX_AGE = 86400L;
    private static final String PATH = "/";

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    UserConverterMapper userConverterMapper;

    @Autowired
    IKaptchaService iKaptchaService;

    @Override
    public MyUserLoginResponse postUserLogin(UserLoginRequest userLoginRequest, HttpServletRequest request, HttpServletResponse response) {

        // 校验验证码是否正确    TODO 优化思路：使用服务调用的方法进行验证码校验
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(userLoginRequest.getCaptcha());
        try {
            iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        } catch (ValidateException e) {
            e.printStackTrace();
            return wrapErrorMsg(UserRetCode.KAPTCHA_CODE_ERROR);
        }

        // 校验用户名和密码(是否错误)
        Example memberExample = new Example(Member.class);
        memberExample.createCriteria()
                .andEqualTo("username",userLoginRequest.getUserName())
                .andEqualTo("password", AesUtils.encrypt(userLoginRequest.getUserPwd(),userLoginRequest.getUserName()));
        Member member = memberMapper.selectOneByExample(memberExample);
        if (member==null){
            return wrapErrorMsg(UserRetCode.USERORPASSWORD_ERRROR);
        }

        // 校验用户名是否激活
        Example userVerifyExample = new Example(UserVerify.class);
        userVerifyExample.createCriteria().andEqualTo("username",userLoginRequest.getUserName());
        UserVerify userVerify = userVerifyMapper.selectOneByExample(userVerifyExample);
        if ("N".equals(userVerify.getIsVerify())){
            return wrapErrorMsg(UserRetCode.USER_ISVERFIED_ERROR);
        }

        // 通过转换器转进Dto中
        MyUserLoginResponse myUserLoginResponse = userConverterMapper.myConverter(member);

        // 放入成功信息
        myUserLoginResponse.setCode(UserRetCode.SUCCESS.getCode());
        myUserLoginResponse.setMsg(UserRetCode.SUCCESS.getMessage());

        // 添加JWT token   TODO  待验证（信息放置是否正确）
        JSONObject userInfo = new JSONObject();
        userInfo.put("uid",member.getId().toString());
        userInfo.put("username",member.getUsername());
        String msg = JSON.toJSONString(userInfo);
        String token = JwtTokenUtils.builder().msg(msg).build().creatJwtToken();
        myUserLoginResponse.setToken(token);

        // 将token加入response中
        response.setHeader("set-cookie","access_token="+token
                +";Max-Age="+MAX_AGE
                +"; Expires="+(new Date(System.currentTimeMillis()+MAX_AGE))
                +"; Path="+PATH);

        return myUserLoginResponse;
    }

    @Override
    public UserLoginResponseGet getUserLogin(HttpServletRequest request) {

        // TODO 从Header中获取uid
        String userInfo = request.getHeader("user_info");
        System.out.println(userInfo);   // TODO 测试语句
        JSONObject userInfoObj = JSON.parseObject(userInfo, JSONObject.class);
        Long uid = Long.parseLong(userInfoObj.get("uid").toString());


        // 用uid获取file
        Member member = memberMapper.selectByPrimaryKey(uid);
        String file = null;
        if (member!=null){
            file=member.getFile();
        }

        // 封装
        UserLoginResponseGet userLoginResponseGet = new UserLoginResponseGet();
        userLoginResponseGet.setUid(uid);
        userLoginResponseGet.setFile(file);

        return userLoginResponseGet;
    }

    private MyUserLoginResponse wrapErrorMsg(UserRetCode userRetCode) {
        MyUserLoginResponse myUserLoginResponse = new MyUserLoginResponse();
        myUserLoginResponse.setCode(userRetCode.getCode());
        myUserLoginResponse.setMsg(userRetCode .getMessage());
        return myUserLoginResponse;
    }

}
